package cn.ratel.kit;

import cn.ratel.tool.TypeConverter;
import com.google.common.base.Preconditions;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;

public class PropKit {
	private static Logger log = LoggerFactory.getLogger(PropKit.class);
	private static Map<String, String> config = new HashMap<>();

	private PropKit() {
	}

	public static void use(String... files) {
		for (String file : files) {
			Properties properties = new Properties();
			try {
				properties.load(PropKit.class.getClassLoader().getResourceAsStream(file));
			} catch (IOException e) {
				throw new RuntimeException("read file error : " + file);
			}
			for (Map.Entry<Object, Object> entry : properties.entrySet()) {
				Preconditions.checkArgument(!config.containsKey(entry.getKey().toString()), "prop key has already exist : " + entry.getKey().toString());
				config.put(entry.getKey().toString(), entry.getValue().toString());
			}
		}
	}

	public static String get(String key) {
		return TypeConverter.convert(String.class, config.get(key));
	}

	public static String get(String key, String defaultValue) {
		if (config.containsKey(key)) {
			return get(key);
		}
		return defaultValue;
	}

	public static Integer getInt(String key) {
		return TypeConverter.convert(Integer.class, config.get(key));
	}

	public static Integer getInt(String key, Integer defaultValue) {
		if (config.containsKey(key)) {
			return getInt(key);
		}
		return defaultValue;
	}

	public static Boolean getBoolean(String key) {
		return TypeConverter.convert(Boolean.class, config.get(key));
	}

	public static Boolean getBoolean(String key, Boolean defaultValue) {
		if (config.containsKey(key)) {
			return getBoolean(key);
		}
		return defaultValue;
	}

	public static boolean containsKey(String key) {
		return config.containsKey(key);
	}

}
